﻿using Ev.CaiPiao.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Media;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace Ev.CaiPiao
{
    public partial class Form1 : Form
    {
        SoundPlayer soundplayer = new SoundPlayer();

        List<string> strListEmail = new List<string>();

        public dl luser { get; set; }

        XmlConfigUtil util = new XmlConfigUtil(StaticData.xmlUrlPath);

        //初始化xml
        XmlDocument xmlDoc = new XmlDocument();
        XmlElement xmlRoot;

        public Form1()
        {
            Login ll = new Login();
            ll.ShowDialog();
            if (ll.loginUser == null || ll.loginUser.UID <= 0)
            {
                this.Close();
                return;
            }
            luser = ll.loginUser;

            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Interval = 1000;
            labelTime.Text = "10";
            timer1.Tick += Timer1_Tick;
            timer1.Start();

            if (File.Exists(StaticData.xmlUrlPath))
                xmlDoc.Load(StaticData.xmlUrlPath);
            else
                xmlDoc.LoadXml("<XmlConfig />");
            xmlRoot = (XmlElement)xmlDoc.ChildNodes[1];

            ReLoadData();

            initData();
        }



        private void Timer1_Tick(object sender, EventArgs e)
        {
            var s = Convert.ToInt16(labelTime.Text);
            s--;
            if (s <= 0)
            {
                var mtoken = new Task().getToken(luser.LoginId, luser.Pwd);
                if (mtoken != luser.Token)
                {
                    timer1.Stop();
                    MessageBox.Show("当前账号在其他地方登录");
                    this.Close();
                }

                initData();
                s = 60;
            }
            labelTime.Text = s.ToString();
        }

        void initData()
        {

            DataTable dt = new DataTable();//建立个数据表
            dt.Columns.Add(new DataColumn("pNo", typeof(int)));//彩票名称
            dt.Columns.Add(new DataColumn("pName", typeof(string)));//彩票名称
            dt.Columns.Add(new DataColumn("qNo", typeof(string)));//期号
            dt.Columns.Add(new DataColumn("jNo", typeof(string)));//奖号
            dt.Columns.Add(new DataColumn("pDate", typeof(string)));//时间
            dt.Columns.Add(new DataColumn("上期期号", typeof(string)));
            dt.Columns.Add(new DataColumn("上期奖号", typeof(string)));
            dt.Columns.Add(new DataColumn("上期时间", typeof(string)));
            dt.Columns.Add(new DataColumn("间隔时差/安全阀", typeof(string)));
            dt.Columns.Add(new DataColumn("期数差", typeof(string)));

            //获取类型列表
            var nodeList = xmlRoot.SelectNodes(StaticData.cpType);
            for (int i = 0; i < nodeList.Count; i++)
            {
                var item = nodeList[i];

                var nodeName = item.SelectSingleNode(StaticData.cpName);
                var nodeDate = item.SelectSingleNode(StaticData.cpDate);
                var nodeUrl = item.SelectSingleNode(StaticData.cpApiUrl);

                try
                {
                    var dataDict = new Common.Task().GetHttpPost(nodeUrl.InnerText);
                    var dList = dataDict.ToList();

                    if (dList != null && dList.Count() > 1)
                    {
                        DataRow dr;//行
                        dr = dt.NewRow();
                        dr["pNo"] = i;
                        dr["pName"] = nodeName.InnerText;
                        dr["qNo"] = dList[0].Key;
                        dr["jNo"] = dList[0].Value.number;
                        dr["pDate"] = dList[0].Value.dateline;
                        dr["上期期号"] = dList[1].Key;
                        dr["上期奖号"] = dList[1].Value.number;
                        dr["上期时间"] = dList[1].Value.dateline;
                        var sSplid = (Convert.ToDateTime(dList[0].Value.dateline) - Convert.ToDateTime(dList[1].Value.dateline)).Minutes;
                        dr["间隔时差/安全阀"] = sSplid + "/" + nodeDate.InnerText;
                        dr["期数差"] = Convert.ToInt64(dList[0].Key) - Convert.ToInt64(dList[1].Key);
                        dt.Rows.Add(dr);//在表的对象的行里添加此行
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("异常信息：" + ex.Message);
                    continue;
                }
            }
            this.dataGridView1.DataSource = dt;
        }


        void initSettingData()
        {
            ReLoadData();
        }


        #region 设置问题

        #region 绑定分类和问题数据

        private void ReLoadData()
        {
            var xmlItemsType = xmlRoot.SelectNodes(StaticData.cpType);
            if (xmlItemsType != null)
            {
                var listType = new List<modelXml>();
                foreach (XmlNode item in xmlItemsType)
                {
                    var nodeName = item.SelectSingleNode(StaticData.cpName);
                    var nodeDate = item.SelectSingleNode(StaticData.cpDate);
                    var nodeUrl = item.SelectSingleNode(StaticData.cpApiUrl);

                    modelXml model = new modelXml();
                    model.名称 = nodeName.InnerText;
                    model.安全阀 = Convert.ToInt32(nodeDate.InnerText);
                    model.接口地址 = nodeUrl.InnerText;
                    listType.Add(model);
                }

                this.dataGridView2.DataSource = new BindingList<modelXml>(listType);

            }
        }

        #endregion

        /// <summary>
        /// 添加url
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtName.Text) || string.IsNullOrEmpty(this.txtDate.Text) || string.IsNullOrEmpty(this.txtUrl.Text) || string.IsNullOrEmpty(this.txtEmail.Text))
            {
                MessageBox.Show("请先完成非空验证");
                return;
            }
            var pdate = 0.0;
            try
            {
                pdate = Convert.ToDouble(this.txtDate.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("请正确输入时间间隔");
                return;
            }

            var nodeCpType = xmlDoc.CreateElement(StaticData.cpType);
            nodeCpType.SetAttribute(StaticData.cpName, txtName.Text);
            //名称
            var nodeCpName = xmlDoc.CreateElement(StaticData.cpName);
            nodeCpName.InnerText = txtName.Text;
            nodeCpType.AppendChild(nodeCpName);
            //时间
            var nodeCpDate = xmlDoc.CreateElement(StaticData.cpDate);
            nodeCpDate.InnerText = txtDate.Text;
            nodeCpType.AppendChild(nodeCpDate);
            //api
            var nodeCpUrl = xmlDoc.CreateElement(StaticData.cpApiUrl);
            nodeCpUrl.InnerText = txtUrl.Text;
            nodeCpType.AppendChild(nodeCpUrl);

            //保存报警邮箱收件箱
            XmlNode nodeEmail = xmlRoot.SelectSingleNode(StaticData.cpEmail);
            nodeEmail.InnerText = txtEmail.Text;

            xmlRoot.AppendChild(nodeCpType);

            xmlDoc.Save(StaticData.xmlUrlPath);

            ReLoadData();

            this.txtName.Text = "";
            this.txtDate.Text = "20";
            this.txtUrl.Text = "";
        }

        #endregion

        private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            string strSplid = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["间隔时差/安全阀"].Value);
            var sList = strSplid.Split('/');
            if (sList.Length != 2)
            {
                return;
            }
            var s1 = sList[0];
            var s2 = sList[1];
            if (Convert.ToInt32(s1) < Convert.ToInt32(s2))
            {
                dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;

                XmlNode nodeEmail = xmlRoot.SelectSingleNode(StaticData.cpEmail);

                var qNo = dataGridView1.Rows[e.RowIndex].Cells["qNo"].Value;

                var strContent = dataGridView1.Rows[e.RowIndex].Cells["pName"].Value
                    + " 期号：" + qNo
                    + " 奖号：" + dataGridView1.Rows[e.RowIndex].Cells["jNo"].Value
                    + " 时间：" + dataGridView1.Rows[e.RowIndex].Cells["pDate"].Value + " \r\n"
                    + " 上期期号：" + dataGridView1.Rows[e.RowIndex].Cells["上期期号"].Value
                    + " 上期奖号：" + dataGridView1.Rows[e.RowIndex].Cells["上期奖号"].Value
                    + " 上期时间：" + dataGridView1.Rows[e.RowIndex].Cells["上期时间"].Value
                    + " 间隔时差/安全阀：" + dataGridView1.Rows[e.RowIndex].Cells["间隔时差/安全阀"].Value
                    + " 期数差：" + dataGridView1.Rows[e.RowIndex].Cells["期数差"].Value;

                var str = dataGridView1.Rows[e.RowIndex].Cells["pName"].Value
                    + " 期号：" + qNo;
                if (strListEmail.Contains(str))
                {
                    return;
                }
                soundplayer.SoundLocation = "OK.wav";
                soundplayer.Load();
                soundplayer.Play();

                //var isSuccess = StaticEmail.sendCode(nodeEmail.InnerText, qNo + "期彩票API报警", strContent);
                //if (isSuccess)
                //{
                strListEmail.Add(str);
                //}

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            initData();
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            ///消除默认选中行
            dataGridView1.ClearSelection();
        }

        private int rowIndex = 0;
        private void dataGridView2_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)//判断是否当前弹起的右键
            {
                rowIndex = e.RowIndex;
                this.dataGridView2.Rows[e.RowIndex].Selected = true;//选中鼠标所在的当前行
                this.dataGridView2.CurrentCell = this.dataGridView2.Rows[e.RowIndex].Cells[1];//默认当前单元格为第一行第一个
                //this.contextMenuStrip1.Show(this.dataGridView1, e.Location);//右键菜单绑定当前位置，也就是第一行第一个
                contextMenuStrip1.Show(Cursor.Position);
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!this.dataGridView2.Rows[this.rowIndex].IsNewRow) //判断当前行是否为空行
            {
                var cName = this.dataGridView2.Rows[rowIndex].Cells["名称"].Value.ToString();

                //删除XML
                var xlist = xmlRoot.SelectNodes(StaticData.cpType);
                foreach (XmlNode item in xlist)
                {
                    var strName = item.Attributes[StaticData.cpName].Value;
                    if (cName == strName)
                    {
                        xmlRoot.RemoveChild(item);
                        xmlDoc.Save(StaticData.xmlUrlPath);
                        break;
                    }
                }
                this.dataGridView2.Rows.RemoveAt(rowIndex);
            }
        }
    }
}
